package com.wmh.baseservice.common.utils.upload.service;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.*;
import com.qcloud.cos.transfer.TransferManager;
import com.qcloud.cos.transfer.TransferManagerConfiguration;
import com.qcloud.cos.transfer.Upload;
import com.qcloud.cos.utils.IOUtils;
import com.wmh.baseservice.common.utils.upload.config.CosConfig;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class CosService {
    @Resource
    private COSClient cosClient;
    @Resource
    private CosConfig config;

    //上传文件
    public String upload(byte[] data, String key) {
        // 存储桶的命名格式为 BucketName-APPID，此处填写的存储桶名称必须为此格式
        String bucketName = config.getQcloudBucketName();
        ObjectMetadata metadate = new ObjectMetadata();
        metadate.setContentLength(data.length);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, new ByteArrayInputStream(data), metadate);

        // 设置文件大小大于等于10MB才使用分块上传
        TransferManagerConfiguration transferManagerConfiguration = new TransferManagerConfiguration();
        transferManagerConfiguration.setMultipartUploadThreshold(10 * 1024 * 1024);
        TransferManager transferManager = new TransferManager(cosClient);
        transferManager.setConfiguration(transferManagerConfiguration);

        //文件上传
        try {
            Upload upload = transferManager.upload(putObjectRequest);
            // 等待传输结束
            // UploadResult uploadResult = upload.waitForUploadResult();
            return key;
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
        // cosClient.shutdown();
    }

    //根据文件key下载文件
    public ResponseEntity<byte[]> downloadImage(String imageName) {
        try {
            // 下载图片
            GetObjectRequest getObjectRequest = new GetObjectRequest(config.getQcloudBucketName(), imageName);
            COSObject cosObject = cosClient.getObject(getObjectRequest);

            // 将 COSObjectInputStream 转换为字节数组
            COSObjectInputStream objectInputStream = cosObject.getObjectContent();
            byte[] imageBytes = IOUtils.toByteArray(objectInputStream);

            // 构建响应体
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_JPEG); // 设置内容类型为图片
            headers.setContentLength(imageBytes.length);
            return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage().getBytes());
        }
        // cosClient.shutdown();
    }

    //根据key获取临时url
    public String geturlBykey(String key) {
        return "https://xxty-1309090453.cos.ap-guangzhou.myqcloud.com/" + key;
    }

    //生成文件路径
    public static String getPath(String prex, String fileName) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String path = simpleDateFormat.format(new Date()) + "/" + UUID.randomUUID().toString().replace("-", "");
        if (prex != null) {
            path = prex + "/" + path;
        }
        return path + "_" + fileName;
    }
}
